package com.cwh.taskcenter.notice.email;

import com.cwh.taskcenter.domain.system.model.MailSendStatusEnum;
import com.cwh.taskcenter.notice.email.api.MailLogService;
import com.cwh.taskcenter.system.mapper.SystemMailLogMapper;
import com.cwh.taskcenter.system.model.SystemMailLogDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static cn.hutool.core.exceptions.ExceptionUtil.getRootCauseMessage;

/**
 * @author cwh
 */
@Slf4j
@Service
public class MailLogServiceImpl implements MailLogService {


    @Autowired
    private SystemMailLogMapper mailLogMapper;


    @Override
    public void updateMailSendResult(Long logId, String messageId, Exception exception) {
        // 1. 成功
        if (exception == null) {
            SystemMailLogDO systemMailLogDO = new SystemMailLogDO();
            systemMailLogDO.setId(logId);
            systemMailLogDO.setSendTime(LocalDateTime.now());
            systemMailLogDO.setSendStatus(MailSendStatusEnum.SUCCESS.getStatus());
            systemMailLogDO.setSendMessageId(messageId);
            mailLogMapper.update(systemMailLogDO);
            return;
        }
        // 2. 失败
        SystemMailLogDO systemMailLogDO = new SystemMailLogDO();
        systemMailLogDO.setId(logId);
        systemMailLogDO.setSendTime(LocalDateTime.now());
        systemMailLogDO.setSendStatus(MailSendStatusEnum.SUCCESS.getStatus());
        systemMailLogDO.setSendException(getRootCauseMessage(exception));
        mailLogMapper.update(systemMailLogDO);
    }
}
